package com.shadow.demo.shiro.controller.sys;

import com.shadow.demo.data.bo.LoginUser;
import com.shadow.demo.common.bo.R;
import com.shadow.demo.shiro.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
public class LocalLoginController {

    @GetMapping("/")
    public String rootPage() {
        return UserUtils.getCurrentLoginUser() == null
                ? loginPage()
                : "index/index";
    }

    /**
     * 登录页面.
     *
     * @return {@link String} 登录页面
     */
    @GetMapping("login")
    public String loginPage() {
        return "login/login-zoneland";
    }

    /**
     * 登录.
     *
     * @return {@link R} 登录结果
     */
    @ResponseBody
    @PostMapping("login")
    public R login(LoginUser loginUser) {
        String account = loginUser.getAccount();
        String password = loginUser.getPassword();
        if (StringUtils.isBlank(account)) {
            return R.fail("用户名为空");
        }
        if (StringUtils.isBlank(password)) {
            return R.fail("密码为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            log.error("未知账户", e);
            return R.fail("未知账户");
        } catch (IncorrectCredentialsException e) {
            log.error("密码不正确", e);
            return R.fail("密码不正确");
        } catch (LockedAccountException e) {
            log.error("账户已锁定", e);
            return R.fail("账户已锁定");
        } catch (ExcessiveAttemptsException e) {
            log.error("用户名或密码错误次数过多", e);
            return R.fail("用户名或密码错误次数过多");
        } catch (AuthenticationException e) {
            log.error("用户名或密码不正确", e);
            return R.fail("用户名或密码不正确");
        }
        if (subject.isAuthenticated()){
            return R.success("/index");
        } else {
            token.clear();
            return R.fail("登录失败");
        }
    }
}
